package net.mingsoft.basic.filter;

import org.apache.shiro.web.filter.authc.*;
import javax.servlet.*;
import javax.servlet.http.*;
import net.mingsoft.base.entity.*;
import cn.hutool.json.*;
import java.io.*;

public class ShiroLoginFilter extends FormAuthenticationFilter
{
    protected boolean isAccessAllowed(final ServletRequest request, final ServletResponse response, final Object mappedValue) {
        final HttpServletRequest request2 = (HttpServletRequest)request;
        final String method = request2.getMethod();
        return "OPTIONS".equalsIgnoreCase(method) || super.isAccessAllowed(request, response, mappedValue);
    }
    
    protected boolean onAccessDenied(final ServletRequest request, final ServletResponse response) throws Exception {
        final HttpServletRequest req = (HttpServletRequest)request;
        final HttpServletResponse resp = (HttpServletResponse)response;
        if (this.isLoginRequest(request, response)) {
            return !this.isLoginSubmission(request, response) || this.executeLogin(request, response);
        }
        final String ajaxHeader = req.getHeader("X-Requested-With");
        if (ajaxHeader != null || req.getHeader("X-TOKEN") != null) {
            resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
            resp.setHeader("Access-Control-Allow-Credentials", "true");
            resp.setContentType("application/json; charset=utf-8");
            resp.setCharacterEncoding("UTF-8");
            resp.setStatus(401);
            final PrintWriter out = resp.getWriter();
            final ResultData data = ResultData.build().code("401").msg("\u672a\u68c0\u6d4b\u5230\u767b\u5f55\u4fe1\u606f\uff0c\u8bf7\u91cd\u65b0\u767b\u5f55");
            out.println(JSONUtil.toJsonStr((Object)data));
            out.flush();
            out.close();
        }
        else {
            this.saveRequestAndRedirectToLogin(request, response);
        }
        return false;
    }
}
